package runInfo;

/**
 * Created by IntelliJ IDEA.
 * User: Mike
 * Date: 10/1/11
 * Time: 3:51 PM
 * To change this template use File | Settings | File Templates.
 */

import java.io.*;
import java.text.DecimalFormat;
import java.util.ArrayList;

public class Flot {

    public static ArrayList<Double> tempTCArr = new ArrayList<Double>();                    // don't have to read in all the data for the type of plotting I'm doing now
    //    public static ArrayList<Double> tempTFArr = new ArrayList<Double>();
    public static ArrayList<Double> tempACArr = new ArrayList<Double>();
    //    public static ArrayList<Double> tempAFArr = new ArrayList<Double>();
//    public static ArrayList<String> dateTime = new ArrayList<String>();
//    public static ArrayList<Double> timeS = new ArrayList<Double>();
    public static ArrayList<Double> milliTime = new ArrayList<Double>();
    public static ArrayList<Double> boilerTemp = new ArrayList<Double>();
    //    public static ArrayList<Double> distTemp = new ArrayList<Double>();
    public static ArrayList<Double> abv = new ArrayList<Double>();
    //    public static ArrayList<Double> abvUncorr = new ArrayList<Double>();
//    public static ArrayList<Integer> bottle = new ArrayList<Integer>();
    public static double totalMin = 0.0;

    public static boolean main(String[] args) {
        boolean completed = false;
        try {

            int nDataRows = CountData();
            ReadinData(nDataRows);
            if (tempTCArr.size() > 2){
                CreateHTML();
                completed = true;
            }
//            CreateHTMLZoom();
            cleanUpArrays();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return completed;
    }

    private static void ReadinData(int nDataRows) throws IOException {

        BufferedReader readbuffer = null;
        String filePathName = "C:\\WhiskeyData\\output.txt";

        try {
            readbuffer = new BufferedReader(new FileReader(filePathName));      //	"" + DatFile.Path[DatFile.Index] + "\\" + DatFile.Name[DatFile.Index]));
        } catch (FileNotFoundException e1) {
            System.out.println("File not found:" + filePathName);
            e1.printStackTrace();
        }
        String strRead;
//		String FileData = currentDir; //not used...
        double startReadHere = 0.01;
        int i = 0;                         // where we are in the file
        int j = 0;                         // where we are in the data
        int k = 0;                         // index to import next set of data aquisition initialization
        int mult = 0;                     // num of restarts
        int multFlag = 0;                 //was there a restart in the last sequence?
        double addtime = 0.0;
        int m = 0;
        boolean UserTimeAdd = false;
        mult = multFlag;

        int sparse = 1;

        if (totalMin > Double.valueOf(TestThreadGUI.getTimeSpan())) {
            startReadHere = (totalMin - Integer.valueOf(TestThreadGUI.getTimeSpan()));
        }
        while ((strRead = readbuffer.readLine()) != null) {
            //System.out.println("i = " + i);
            String splitarray[] = strRead.split("\t");
            if (k == 0) {        // header
                // datetime	min	columnC	columnF	ambientC	ambientF	bottleNumber	correctedAbv	uncorrectedAbv	distillateTempC	boilerTempC
                //	0		1	2		3		4			5			6				7				8				9				10
//                dateTime.clear();
                milliTime.clear();
//                timeS.clear();
                tempTCArr.clear();
//                tempTFArr.clear();
                tempACArr.clear();
//                tempAFArr.clear();
//                bottle.clear();
                abv.clear();
//                abvUncorr.clear();
//                distTemp.clear();
                boilerTemp.clear();
            }
            if (k > 1) {
                if (Double.parseDouble(splitarray[2].trim()) >= startReadHere) {        // read in data
                    if (splitarray.length == 12 && (sparse == 1 || (j % sparse) == 1)) {                         // check to make sure there is data there
//                        dateTime.add(splitarray[0].trim());
                        milliTime.add(Double.parseDouble(splitarray[1].trim()));
//                        timeS.add(Double.parseDouble(splitarray[2].trim()));
                        tempTCArr.add(Double.parseDouble(splitarray[3].trim()));
//                        tempTFArr.add(Double.parseDouble(splitarray[4].trim()));
                        tempACArr.add(Double.parseDouble(splitarray[5].trim()));
//                        tempAFArr.add(Double.parseDouble(splitarray[6].trim()));
//                        bottle.add(Integer.parseInt(splitarray[7].trim()));
                        abv.add(Double.parseDouble(splitarray[8].trim()));
//                        abvUncorr.add(Double.parseDouble(splitarray[9].trim()));
//                        distTemp.add(Double.parseDouble(splitarray[10].trim()));
                        boilerTemp.add(Double.parseDouble(splitarray[11].trim()));
                        j++;
                    }
                }
            }
            k = k + 1;
            i = i + 1;
        }
        readbuffer.close();

        addtime = 0;
    }

    private static int CountData() {
        System.out.println("Reading in DAT file....");                                    // import data from file (DatFile.Index), line by line (i), into arrays (j)
        BufferedReader readbuffer = null;
        String filePathName = "C:\\WhiskeyData\\output.txt";

        try {
            readbuffer = new BufferedReader(new FileReader(filePathName));
        } catch (FileNotFoundException e1) {
            System.out.println("File not found:" + filePathName);
            e1.printStackTrace();
        }
        String strRead;
//		String FileData = currentDir; //not used...
        int i = 0;                         // where we are in the file
        int j = 0;                         // where we are in the data
        int k = 0;                         // index to import next set of data aquisition initialization
        int sparse = 1;
        try {
            while ((strRead = readbuffer.readLine()) != null) {
                //System.out.println("i = " + i);
                String splitarray[] = strRead.split("\t");
                if (k == 0) {        // header
                    // datetime	min	columnC	columnF	ambientC	ambientF	bottleNumber	correctedAbv	uncorrectedAbv	distillateTempC	boilerTempC
                    //	0		1	2		3		4			5			6				7				8				9				10
                }
                if (k > 0) {        // read in data
                    if (splitarray.length == 12 && (sparse == 1 || (j % sparse) == 1)) {                         // check to make sure there is data there
                        totalMin = Double.parseDouble(splitarray[2].trim());
                        j++;
                    }
                }
                k = k + 1;
                i = i + 1;
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        try {
            readbuffer.close();
        }                         //Close the stream to free memory resources on the host computer:
        catch (IOException e1) {
            e1.printStackTrace();
        }
        return j;
    }


    static void CreateHTMLZoom() throws IOException {
//	static void CreateHTML(Double[] runningTime, Double[] colTemp, Double[] boilTemp) throws IOException {

        String Dir = "C:\\WhiskeyData\\flot\\examples\\FlotPlot.html";

        String[] html = new String[100];

/*
        html[52] = "var colTemp = [[";
        for (int i = 1; i < tempTCArr.size(); i++) {
            double time = timeS.get(i) * 1000 * 60 + 1167692400000.0 - (3 * 60 * 60 * 1000.0 * 1000.0 * 1000.0);
            time = milliTime.get(i);
            html[52] = html[52] + String.valueOf(time) + "," + String.valueOf(tempTCArr.get(i));
            if (i < tempTCArr.size() - 1) html[52] = html[52] + "],[";
        }
        html[52] = html[52] + "]];";

        html[53] = "var boilTemp = [[";
        for (int i = 1; i < boilerTemp.size(); i++) {
            double time = timeS.get(i) * 1000 * 60 + 1167692400000.0 - 3 * 60 * 60 * 1000.0 * 1000.0 * 1000.0;
            time = milliTime.get(i);
            html[53] = html[53] + String.valueOf(time) + "," + String.valueOf(boilerTemp.get(i));
            if (i < boilerTemp.size() - 1) html[53] = html[53] + "],[";
        }
        html[53] = html[53] + "]];";

        */

        html[0] = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">";
        html[1] = "<html>";
        html[2] = " <head>";
        html[3] = "    <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">";
        html[4] = "    <title>Flot Examples</title>";
        html[5] = "    <link href=\"layout.css\" rel=\"stylesheet\" type=\"text/css\">";
        html[6] = "    <!--[if lte IE 8]><script language=\"javascript\" type=\"text/javascript\" src=\"../excanvas.min.js\"></script><![endif]-->";
        html[7] = "    <script language=\"javascript\" type=\"text/javascript\" src=\"../jquery.js\"></script>";
        html[8] = "    <script language=\"javascript\" type=\"text/javascript\" src=\"../jquery.flot.js\"></script>";
        html[9] = "";
        html[10] = "    <script language=\"javascript\" type=\"text/javascript\" src=\"../jquery.flot.selection.js\"></script>";
        html[11] = " </head>";
        html[12] = "    <body>";
        html[13] = "    <div style=\"float:left\">";
        html[14] = "      <div id=\"placeholder\" style=\"width:500px;height:300px\"></div>";
        html[15] = "    </div>";
        html[16] = "";
        html[17] = "    ";
        html[18] = "    <div id=\"miniature\" style=\"float:left;margin-left:20px\">";
        html[19] = "      <div id=\"overview\" style=\"width:166px;height:100px\"></div>";
        html[20] = "";
        html[21] = "      <p id=\"overviewLegend\" style=\"margin-left:10px\"></p>";
        html[22] = "    </div>";
        html[23] = "";
        html[24] = "<script id=\"source\">";
        html[25] = "$(function () {";
        html[26] = "    // setup plot";
        html[27] = "    function getData(x1, x2) {";
        html[28] = "        var d = [];";
        html[29] = "        for (var i = 0; i <= 100; ++i) {";
        html[30] = "            var x = x1 + i * (x2 - x1) / 100;";
        html[31] = "            d.push([x, Math.sin(x * Math.sin(x))]);";
        html[32] = "        }";
        html[33] = "";
        html[34] = "        return [";
        html[35] = "            { label: \"sin(x sin(x))\", data: d }";
        html[36] = "        ];";
        html[37] = "    }";
        html[38] = "";
        html[39] = "    var options = {";
        html[40] = "xaxes: [ { mode: 'time' } ],";
        html[41] = "yaxes: [ { min: 0 },{alignTicksWithAxis: position == \"right\" ? 1 : null,position: position,tickFormatter: euroFormatter} ],";
        html[42] = "";
        html[43] = "        legend: { show: false },";
        html[44] = "        series: {";
        html[45] = "            lines: { show: true },";
        html[46] = "            points: { show: true }";
        html[47] = "        },";
        html[48] = "        yaxis: { ticks: 10 },";
        html[49] = "        selection: { mode: \"xy\" }";
        html[50] = "    };";
        html[51] = "";
        html[51] = "";
        html[51] = "";
        html[54] = "";
        html[55] = "";
        html[56] = "    var startData = getData(0, 3 * Math.PI);";
        html[57] = "    ";
        html[58] = "    var plot = $.plot($(\"#placeholder\"),[ { data: colTemp, label: \"Column Temp (C)\" },{ data: boilTemp, label: \"Bottle Number\", yaxis: 2 }],options);";
        html[59] = "";
        html[60] = "    // setup overview";
        html[61] = "    var overview = $.plot($(\"#overview\"), colTemp, {";
        html[62] = "        legend: { show: true, container: $(\"#overviewLegend\") },";
        html[63] = "        series: {";
        html[64] = "            lines: { show: true, lineWidth: 1 },";
        html[65] = "            shadowSize: 0";
        html[66] = "        },";
        html[67] = "        xaxis: { ticks: 4 },";
        html[68] = "        yaxis: { ticks: 3, min: -2, max: 2 },";
        html[69] = "        grid: { color: \"#999\" },";
        html[70] = "        selection: { mode: \"xy\" }";
        html[71] = "    });";
        html[72] = "";
        html[73] = "    // now connect the two";
        html[74] = "    ";
        html[75] = "    $(\"#placeholder\").bind(\"plotselected\", function (event, ranges) {";
        html[76] = "        // clamp the zooming to prevent eternal zoom";
        html[77] = "        if (ranges.xaxis.to - ranges.xaxis.from < 0.00001)";
        html[78] = "            ranges.xaxis.to = ranges.xaxis.from + 0.00001;";
        html[79] = "        if (ranges.yaxis.to - ranges.yaxis.from < 0.00001)";
        html[80] = "            ranges.yaxis.to = ranges.yaxis.from + 0.00001;";
        html[81] = "        ";
        html[82] = "        // do the zooming";
        html[83] = "        plot = $.plot($(\"#placeholder\"), getData(ranges.xaxis.from, ranges.xaxis.to),";
        html[84] = "                      $.extend(true, {}, options, {";
        html[85] = "                          xaxis: { min: ranges.xaxis.from, max: ranges.xaxis.to },";
        html[86] = "                          yaxis: { min: ranges.yaxis.from, max: ranges.yaxis.to }";
        html[87] = "                      }));";
        html[88] = "        ";
        html[89] = "        // don't fire event on the overview to prevent eternal loop";
        html[90] = "        overview.setSelection(ranges, true);";
        html[91] = "    });";
        html[92] = "    $(\"#overview\").bind(\"plotselected\", function (event, ranges) {";
        html[93] = "        plot.setSelection(ranges);";
        html[94] = "    });";
        html[95] = "});";
        html[96] = "</script>";
        html[97] = "";
        html[98] = " </body>";
        html[99] = "</html>";


//		String output = html1 + colTemps + boilTemps + html2;

        FileWriter write = new FileWriter(Dir, false);
        PrintWriter text = new PrintWriter(write, false);
//		System.out.println(output);
        for (int i = 0; i < html.length; i++) {
            text.println(html[i]);
        }
        text.flush();
        write.close();
        text.close();
        write = null;
        text = null;

    }


    static void CreateHTML() throws IOException {

        String Dir = "C:\\WhiskeyData\\flot\\examples\\FlotPlot.html";

        String[] html = new String[37];
        html[0] = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">";
        html[1] = "<html>";
        html[2] = "<head>";
        html[3] = "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">";
        html[4] = "<title>Flot Examples</title>";
        html[5] = "<link href=\"layout.css\" rel=\"stylesheet\" type=\"text/css\">";
        html[6] = "<!--[if lte IE 8]><script language=\"javascript\" type=\"text/javascript\" src=\"../excanvas.min.js\"></script><![endif]-->";
        html[7] = "<script language=\"javascript\" type=\"text/javascript\" src=\"../jquery.js\"></script>";
        html[8] = "<script language=\"javascript\" type=\"text/javascript\" src=\"../jquery.flot.js\"></script>";
        html[9] = "</head>";
        html[10] = "<body>";
        html[11] = "<div id=\"placeholder\" style=\"width:600px;height:300px;\"></div>";
        html[12] = "<script type=\"text/javascript\">";
        html[13] = "$(function () {";

        html[14] = "var colTemp = [[";
        for (int i = 1; i < tempTCArr.size(); i++) {
            double time = milliTime.get(i) - (4 * 60 * 60 * 1000.0) + (30 * 24 * 60 * 60 * 1000.0);    // - time zone correction   + month correction
            html[14] = html[14] + String.valueOf(time) + "," + String.valueOf(tempTCArr.get(i));
//            html[14] = html[14] + String.valueOf(timeS.get(i) * 1000 * 60 + 1167692400000.0 - 1000 * 60 * 3) + "," + String.valueOf(tempTCArr.get(i));
            if (i < tempTCArr.size() - 1) html[14] = html[14] + "],[";
        }
        html[14] = html[14] + "]];";

        html[15] = "var boilTemp = [[";
        for (int i = 1; i < boilerTemp.size(); i++) {
            double time = milliTime.get(i) - (4 * 60 * 60 * 1000.0) + (30 * 24 * 60 * 60 * 1000.0);    // - time zone correction   + month correction
            html[15] = html[15] + String.valueOf(time) + "," + String.valueOf(boilerTemp.get(i));
//            html[15] = html[15] + String.valueOf(timeS.get(i) * 1000 * 60 + 1167692400000.0 - 1000 * 60 * 3) + "," + String.valueOf(boilerTemp.get(i));
            if (i < boilerTemp.size() - 1) html[15] = html[15] + "],[";
        }
        html[15] = html[15] + "]];";

        html[16] = "function euroFormatter(v, axis) {return v.toFixed(axis.tickDecimals) +\"C\";}";
        html[17] = "function doPlot(position) {";
        html[18] = "$.plot($(\"#placeholder\"),";
        html[19] = "[ { data: colTemp, label: \"Column Temp (C)\" },";
        html[20] = "{ data: boilTemp, label: \"Boiler Temp\", yaxis: 2 }],";
        html[21] = "{xaxes: [ { mode: \'time\' } ],";
//        html[22] = "yaxes: [ { min: 0 },";
        html[22] = "yaxes: [ { },";
        html[23] = "{alignTicksWithAxis: position == \"right\" ? 1 : null,";
        html[24] = "position: position,";
        html[25] = "tickFormatter: euroFormatter";
        html[26] = "} ],";
        html[27] = "legend: { position: \'sw\' }";
        html[28] = "});}";
        html[29] = "doPlot(\"right\");";
        html[30] = "";
//        html[30] = "$(\"button\").click(function () {doPlot($(this).text());});";
        html[31] = "var colTemp = null;";
        html[32] = "var boilTemp = null;";
        html[33] = "});";
        html[34] = "</script>";
        html[35] = "</body>";
        html[36] = "</html>";

//		String output = html1 + colTemps + boilTemps + html2;

        FileWriter write = new FileWriter(Dir, false);
        PrintWriter text = new PrintWriter(write, false);
//		System.out.println(output);
        for (int i = 0; i < html.length; i++) {
            text.println(html[i]);
        }
        text.flush();
        write.close();
        text.close();
        write = null;
        text = null;

    }

    private static void cleanUpArrays() {
//        dateTime.clear();
//        timeS.clear();
        tempTCArr.clear();
//        tempTFArr.clear();
        tempACArr.clear();
//        tempAFArr.clear();
//        bottle.clear();
        abv.clear();
//        abvUncorr.clear();
//        distTemp.clear();
        boilerTemp.clear();
    }


}

